package com.lin.ovc.pomodoro.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lin.ovc.pomodoro.entity.User;
import com.lin.ovc.pomodoro.service.UserService;
import com.lin.ovc.pomodoro.utils.JwtHelper;
import com.lin.ovc.pomodoro.utils.R;
import com.lin.ovc.pomodoro.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
//        User user = (User)authResult.getPrincipal();
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("name", user.getUsername());

        //根据用户名生成token
        String token = JwtHelper.createToken(userService.getOne(wrapper).getId(), user.getUsername());
        System.out.println(token);
        //把用户名称和用户权限列表放到redis
//        redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(),user.getPermissionValueList());

//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
//        if (authentication != null && authentication.isAuthenticated()) {
//            return "用户: " + authentication.getName();
//        } else {
//            return "用户未登录";
//        }

        ResponseUtil.out(httpServletResponse, R.ok().data("token", token).message(authentication.getName()));
    }

}